"ui";
var x = device.width;
var y = device.height
var 配置 = storages.create("ABC");
ui.layout(
    <linear orientation="vertical">
        <frame w="{{x}}px"h="{{y}}px">
            <card h="480"cardCornerRadius="20dp" cardElevation="2dp" layout_gravity="center">
                <vertical>
                    <horizontal>
                        <text text="账号"/>
                        <input id="账号"w="*"/>
                    </horizontal>
                    <horizontal>
                        <text text="密码"/>
                        <input id="密码"w="*"/>
                    </horizontal>
                    <button id="保存数据"text="保存数据"/>
                    <button id="测试数据"text="测试数据"/>


                    <horizontal>
                    <text text="输入url"/>
                    <input id="forurl" w="*"/>
                    </horizontal>
                    <button id="发起get请求" text="发起get请求"/>
                    <button id="发起post请求" text="发起post请求"/>
                </vertical>
            </card>
        </frame>
    </linear>
);

var 数据 = 配置.get("账号密码");
if (数据) {
    ui.账号.setText(数据.账号)
    ui.密码.setText(数据.密码)
}
ui.保存数据.click(() => {
    账号 = ui.账号.text()
    密码 = ui.密码.text()
    配置.put("账号密码", {
        "账号": 账号,
        "密码": 密码
    });
    toast("账号密码已记录")
})

ui.测试数据.click(() => {
    toastLog("账号："+ 配置.get("账号密码").账号);
    toastLog("密码："+ 配置.get("账号密码").密码);
})

ui.发起get请求.click(() => {
    //在Android 4.0以上，网络连接不能放在主线程上;这个设计是为了防止网络请求时间过长而导致界面假死的情况发生
    threads.start(function(){
        var url = ui.forurl.text()
        var res = send_get(url)
    })
})

ui.发起post请求.click(() => {
    threads.start(function(){
        var url = ui.forurl.text()
        var res = send_post(url,{})
    })
})

function send_get(url){
    url = url ? url:"https://www.sojson.com/open/api/weather/json.shtml?city=广州";
    var res = http.get(url,{
        headers: {
            'Accept-Language': 'zh-cn,zh;q=0.5',
            'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'
        }
    });
    if(res.statusCode != 200){
        toast("请求失败: " + res.statusCode );
    }else{
        toast("请求成功");
    }
    toastLog("响应头："+res.headers)
    toastLog("响应体："+res.body.string());
}

function send_post(url, postdata){
    url = url ? url :"http://www.tuling123.com/openapi/api";
    var res = http.post(url, postdata,{
        headers: {
            'Accept-Language': 'zh-cn,zh;q=0.5',
            'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'
        }
    });
    if(res.statusCode != 200){
        toast("请求失败: " + res.statusCode + " " + res.statusMessage);
    }else{
       toast("请求成功");
    }
    toastLog("响应头："+res.headers)
    toastLog("响应体："+res.body.string());
}